package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.StageDefinePropertyOriginal;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * Created by lenovo on 2016/7/4.
 * 阶段自定义属性详情
 */
public class StageDefinePropertyDetailFragment extends BaseFragment
    implements View.OnClickListener {
  protected static final String EXTRA_CONTENT =
      "com.isunland.managesystem.ui.StageDefinePropertyDetailFragment.EXTRA_CONTENT";
  protected static final String EXTRA_VALUE =
      "com.isunland.managesystem.ui.StageDefinePropertyDetailFragment.EXTRA_VALUE";
  protected static final int FILE_VALUE = 0;
  protected static final int DATE_VALUE = 1;
  protected static final int EDIT_KIND = 2;
  protected static final int REQUEST_SAVE = 3;
  protected static final int REQUEST_DEL = 4;

  protected String mFilePath = "";//文件本地路径
  protected String mFilePathServer = "";//文件服务端路径
  protected String mfileName = "";
  private StageDefinePropertyOriginal.StageDefinePropertyContent content;
  private CustomerDialog extContent;
  private EditText mEtPropertyName;
  private TextView mTvPropertyType;
  private EditText mEtPropertyValue;
  private ImageView mIbPropertyValue;
  private EditText mEtRemark;
  private TextView mTvRegister;
  private TextView mTvRegisteredTime;
  private String mSdefpropEditKind = "";//编辑类型
  private String mId;//记录id

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom(R.string.definedProperty);
    content =
        (StageDefinePropertyOriginal.StageDefinePropertyContent) getArguments().getSerializable(
            EXTRA_CONTENT);
    extContent = (CustomerDialog) getArguments().getSerializable(EXTRA_VALUE);
    if (content != null) {
      mSdefpropEditKind = content.getSdefpropEditKind();
      mId = content.getId();
      mFilePathServer = content.getSdefpropPath();
    } else {
      mId = UUID.randomUUID().toString();
      mSdefpropEditKind = "01";//添加默认是文字
    }
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_stage_property, container, false);
    findView(v);
    if (content != null) {
      initDate();
    } else {
      mTvPropertyType.setText(R.string.words);
      mIbPropertyValue.setVisibility(View.GONE);
      mTvRegister.setText(mCurrentUser.getRealName());
      mTvRegisteredTime.setText(MyDateUtil.dateToString(new Date(), MyDateUtil.TYPE_DATE));
    }
    return v;
  }

  private void findView(View v) {
    mEtPropertyName = (EditText) v.findViewById(R.id.et_propertyName);
    mTvPropertyType = (TextView) v.findViewById(R.id.tv_propertyType);
    ImageView mIbPropertyType = (ImageView) v.findViewById(R.id.ib_propertyType);
    mEtPropertyValue = (EditText) v.findViewById(R.id.et_propertyValue);
    mIbPropertyValue = (ImageView) v.findViewById(R.id.ib_propertyValue);
    mEtRemark = (EditText) v.findViewById(R.id.et_remark);
    mTvRegister = (TextView) v.findViewById(R.id.tv_register);
    mTvRegisteredTime = (TextView) v.findViewById(R.id.tv_registered_time);

    mIbPropertyType.setOnClickListener(StageDefinePropertyDetailFragment.this);
    mIbPropertyValue.setOnClickListener(StageDefinePropertyDetailFragment.this);
  }

  @Override public void onClick(View view) {
    switch (view.getId()) {
      case R.id.ib_propertyType:
        showDialog(EDIT_KIND);
        break;
      case R.id.ib_propertyValue:
        if ("02".equalsIgnoreCase(mSdefpropEditKind)) {
          showDialog(DATE_VALUE);
        } else if ("03".equalsIgnoreCase(mSdefpropEditKind)) {
          showDialog(FILE_VALUE);
        }
        break;
      default:
        break;
    }
  }

  private void showDialog(int requestCode) {
    DialogFragment dialog = null;
    switch (requestCode) {
      case EDIT_KIND:
                /*编辑类型
                 1.如果是01,代表是文本类型,需要输入字符串;输入的值直接存到sdefpropValue中
                2.如果是02,代表是日期,需要显示日期选择输入框;
                3.如果是03,代表是文档类型,需要上传文件,出现文件上传对话框。*/
        dialog = new EditKindDialogFragment();
        break;
      case DATE_VALUE:
        //时间
        dialog = new BaseYMDTimeDialogFragment();
        break;
      case FILE_VALUE:
        //附件
        dialog = ExtraUpLoadDialogFragment.newInstance(mFilePath);
        break;
    }
    FragmentManager fm = getActivity().getSupportFragmentManager();
    if (dialog != null) {
      dialog.setTargetFragment(StageDefinePropertyDetailFragment.this, requestCode);
    }
    dialog.show(fm, "");
  }

  private void initDate() {
    //初始化控件
    mEtPropertyName.setText(content.getSdefpropName());
    if ("01".equalsIgnoreCase(mSdefpropEditKind)) {
      mTvPropertyType.setText(R.string.words);
      mIbPropertyValue.setVisibility(View.GONE);
    } else if ("02".equalsIgnoreCase(mSdefpropEditKind)) {
      mTvPropertyType.setText(R.string.data);
      mEtPropertyValue.setEnabled(false);
    } else if ("03".equalsIgnoreCase(mSdefpropEditKind)) {
      mTvPropertyType.setText(R.string.file);
      mEtPropertyValue.setTextColor(Color.BLUE);

      mEtPropertyValue.setFocusable(false);//不可编辑
      mEtPropertyValue.setClickable(true);//可以点击
    }
    mEtPropertyValue.setText(content.getSdefpropValue());
    mEtRemark.setText(content.getRemark());
    mTvRegister.setText(content.getRegStaffName());
    mTvRegisteredTime.setText(content.getRegDate());

    //点击附件名，下载附件
    mEtPropertyValue.setOnClickListener(new View.OnClickListener() {

      @Override public void onClick(View v) {

        if (!TextUtils.isEmpty(mFilePathServer) || !TextUtils.isEmpty(mFilePath)) {
          ExtraDownLoadDialogFragment dialog = null;
          if (!TextUtils.isEmpty(mFilePathServer) && TextUtils.isEmpty(mFilePath)) {
            dialog = ExtraDownLoadDialogFragment.newInstance("", content.getSdefpropPath());
          } else if (!TextUtils.isEmpty(mFilePath) && TextUtils.isEmpty(mFilePathServer)) {
            dialog = ExtraDownLoadDialogFragment.newInstance(mFilePath, "");
          }
          FragmentManager fm = getActivity().getSupportFragmentManager();
          dialog.show(fm, "");
        }
      }
    });
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_already_done, menu);
    menu.getItem(0).setTitle(R.string.save);
    menu.getItem(1).setTitle(R.string.delete);
    if (content == null) {
      menu.getItem(1).setVisible(false).setEnabled(false);
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        return true;
      //保存
      case R.id.menu_item_recover:
        //                //当前登录人是阶段负责人或项目经理是可编辑保存
        //                if ((mUser.getJobNumber()).equals(extContent.getId()) || (mUser.getJobNumber()).equals(extContent.getName())) {
        //
        //                    if ("01".equalsIgnoreCase(content.getSdefpropEditKind()) || "02".equalsIgnoreCase(content.getSdefpropEditKind())) {
        //                       volleyPostSave();
        //                    } else {
        //                        volleyPostFileSave();
        //                    }
        //                } else {
        //                    ToastUtil.show(R.string.pm_regist);
        //                }

        if (!TextUtils.isEmpty(mEtPropertyName.getText().toString())) {
          volleyPostSave();
        } else {
          ToastUtil.show(R.string.completeWrite);
        }

        return true;

      //删除
      case R.id.menu_item_reminders:
        //当前登录人是阶段负责人或项目经理是可编辑保存
        //                if ((mUser.getJobNumber()).equals(extContent.getId()) || (mUser.getJobNumber()).equals(extContent.getName())) {

        volleyPostDelete();

        //                } else {
        //                    ToastUtil.show(R.string.pm_regist);
        //                }

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  public void volleyPostDelete() {
    String delUrl = ApiConst.getAbsoluteUrl(ApiConst.ULR_STAGE_PROPERTY_DEL);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", content.getId());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(delUrl, params, response(REQUEST_DEL));
  }

  private void volleyPostSave() {
    String saveUrl = ApiConst.getAbsoluteUrl(ApiConst.ULR_STAGE_PROPERTY_SAVE);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    params.put("dataStatus", "new");
    params.put("memberCode", mCurrentUser.getMemberCode());
    params.put("stageId", extContent.getMemberCode());//阶段id
    params.put("stageName", extContent.getDept());//阶段名称
    params.put("sdefpropName", mEtPropertyName.getText().toString());//名称
    params.put("sdefpropEditKind", mSdefpropEditKind);//类型
    params.put("sdefpropValue", mEtPropertyValue.getText().toString());//属性值
    params.put("remark", mEtRemark.getText().toString());//备注
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(saveUrl, params, response(REQUEST_SAVE));
  }

  private VolleyResponse response(final int requestCode) {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        try {
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {

            if (REQUEST_SAVE == requestCode) {
              //是否有附件
              if (!TextUtils.isEmpty(mFilePath)) {
                volleyPostFile();
              }
              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
            }
            if (REQUEST_DEL == requestCode) {
              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
            }
            ToastUtil.show(R.string.success_operation);
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }
    };
  }

  private void volleyPostFile() {
    new FileNetWorkUtil(getActivity()).upLoadFilePath(mFilePath, ApiConst.URL_UPLOAD_FILE, null,
        "app", "project.dd_project_sdefprop_data", mId, null, false, "sdefpropPath");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    //编辑类型
    if (requestCode == EDIT_KIND) {
      clearExtraFile();
      CustomerDialog editKindContent =
          (CustomerDialog) data.getSerializableExtra(EditKindDialogFragment.EXTRA_KIND);
      mSdefpropEditKind = editKindContent.getId();
      String kindName = editKindContent.getName();
      mTvPropertyType.setText(kindName);
      if ("01".equalsIgnoreCase(mSdefpropEditKind)) {
        mIbPropertyValue.setVisibility(View.GONE);
        mEtPropertyValue.setFocusableInTouchMode(true);//获取焦点
        mEtPropertyValue.setEnabled(true);//可编辑
      } else if ("02".equalsIgnoreCase(mSdefpropEditKind)) {
        mIbPropertyValue.setVisibility(View.VISIBLE);
        mEtPropertyValue.setEnabled(false);
      } else if ("03".equalsIgnoreCase(mSdefpropEditKind)) {
        mEtPropertyValue.setText("");
        mEtPropertyValue.setTextColor(Color.BLUE);
        mIbPropertyValue.setVisibility(View.VISIBLE);
        mEtPropertyValue.setFocusable(false);//不可编辑
        mEtPropertyValue.setClickable(true);//可以点击
      }
    }
    if (requestCode == DATE_VALUE) {
      clearExtraFile();
      Date date = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      String dateStr = MyDateUtil.dateToString(date, MyDateUtil.TYPE_DATE);
      mEtPropertyValue.setText(dateStr);
    }
    if (requestCode == FILE_VALUE) {
      String result = data.getStringExtra(ExtraUpLoadDialogFragment.EXTRA_RESULT);
      //            if (ExtraUpLoadDialogFragment.VALUE_CLEAR.equalsIgnoreCase(result)) {
      clearExtraFile();
      //            } else {
      mFilePath = result;
      if (mFilePath != null) {
        mfileName = FileUtil.getFileNameByFilePath(mFilePath);
        mEtPropertyValue.setText(mfileName);
      }
      //            }
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  public void clearExtraFile() {
    mFilePath = "";
    mfileName = "";
    mFilePathServer = "";
    mEtPropertyValue.setText("");
  }

  public static StageDefinePropertyDetailFragment newInstence(
      StageDefinePropertyOriginal.StageDefinePropertyContent content) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_CONTENT, content);
    StageDefinePropertyDetailFragment mfragment = new StageDefinePropertyDetailFragment();
    mfragment.setArguments(bundle);
    return mfragment;
  }

  public static StageDefinePropertyDetailFragment newInstence(
      StageDefinePropertyOriginal.StageDefinePropertyContent content, CustomerDialog extContent) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_CONTENT, content);
    bundle.putSerializable(EXTRA_VALUE, extContent);
    StageDefinePropertyDetailFragment mfragment = new StageDefinePropertyDetailFragment();
    mfragment.setArguments(bundle);
    return mfragment;
  }
}
